package com.anlu.concurrent.ch2.forkjoin.sum;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/6 15:57
 */
public class SumArray {
    private static class SumTask extends RecursiveTask<Integer>{
        private final static int THRESHOLD = MakeArray.ARRAY_LENGTH/10;
        //表示我们要实际统计的数组
        private int[] src;
        //开始统计的下标
        private int fromIndex;
        //统计到哪里结束的下标
        private int toIndex;

        public SumTask(int[] src, int fromIndex, int toIndex) {
            this.src = src;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }
        @Override
        protected Integer compute() {
            if(toIndex-fromIndex<THRESHOLD){
                int count = 0;
                for (int i=fromIndex;i<toIndex;i++){
                    count = count + src[i];
                }
                return count;
            }else{
                //fromIndex....mid....toIndex
                //1...................70....100
                int mid = (fromIndex+toIndex)/2;
                SumTask left = new SumTask(src,fromIndex,mid);
                SumTask right = new SumTask(src,mid+1,toIndex);
                invokeAll(left,right);
                return left.join()+right.join();
            }
        }
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        int[] src = MakeArray.makeArray();

        SumTask innerFind = new SumTask(src,0,src.length-1);
        long start = System.currentTimeMillis();

        // 同步调用
        pool.invoke(innerFind);
        System.out.println("Task is running ");
        System.out.println("The count is "+innerFind.join()
                +" spend time:"+(System.currentTimeMillis()-start)+"ms");

    }
}
